#include "ET++.ph"
#include "Converter.h"

#include "Class.h"
#include "Data.h"
#include "Text.h"
#include "TypeMatcher.h"

//---- AsciiTypeMatcher --------------------------------------------------------

class AsciiTypeMatcher: public TypeMatcher {
public:
	AsciiTypeMatcher() : TypeMatcher(cDocTypeAscii, 0, 0, TRUE, 10001)
		{ }
	bool MatchContents(Data*, const char*, int);
	bool MatchPathName(Data*, const char*, int)
		{ return FALSE; }
};

static AsciiTypeMatcher asciimatcher;

bool AsciiTypeMatcher::MatchContents(Data*, const char *bp, int l)
{
	while (l-- > 0)
		if (!Isascii(*bp++))
			return FALSE;
	return TRUE;
}

//---- AsciiConverter ----------------------------------------------------------

class AsciiConverter : public Converter {
public:
	MetaDef(AsciiConverter);
	AsciiConverter()
		{ }
	const char *AsString()
		{ return "ASCII Text"; }
	Object *Convert(Data *data, Class *want);
	bool CanConvert(Data *data, Class *want)
		{ return (data->Type() == cDocTypeAscii || data->IsAscii())
					&& want->isKindOf(Meta(Text)); }
	bool CanConvertTo(Object *op)
		{ return op->IsKindOf(Text); }
	bool ConvertTo(Data *data, Object *op);
};

NewMetaImpl0(AsciiConverter,Converter);

Object *AsciiConverter::Convert(Data *data, Class *want)
{
	IStream from(data->GetStreamBufForReading(), 0, TRUE);
	Text *t= (Text*)want->Proto()->New();
	if (t)
		t->ReadFromAsPureText(from, data->SizeHint());
	return t;
}

bool AsciiConverter::ConvertTo(Data *data, Object *op)
{
	Text *t= Guard(op, Text);
	OStream to(data->GetStreamBufForWriting(), TRUE);
	if (t)
		t->PrintOnAsPureText(to);
	return TRUE;
}

